import pyautogui
import uiautomation as auto

from _qAutomation.config.config import *
from _qAutomation.utils.logInfo import *


def go_windows():
    sleep_little()
    auto.SendKeys("{win}D")

def open_qq():
    # 打开QQ有几种可能：
    # 1. 第一次打开已经具备的账号 ==> 可以直接点击登录 或 “添加账号” 进行登录
    # 2. 当前已有QQ登录 ==> 直接进入输入账号密码的界面,仅需要判断 “输入QQ号”是否存在
    # 3. 未知情况 ==> 出现扫码登录的面板，底下有 “账密登录” 的选项

    # 控件准备阶段
    control_qqApp = auto.ListItemControl(searchDepth=30, Name="QQ")

    # 打开桌面上的腾讯QQ
    if not control_qqApp.Exists():
        log(levelConstant.INFO, "当前桌面没有QQ 正在启用Windows搜索...")
        sleep_little()
        auto.SendKeys("{win}")
        pyautogui.write(appName, interval=0.2)
        auto.SendKeys("{enter}{enter}")
    else:
        control_qqApp.DoubleClick()
    sleep_little2()

def login_qq():

    # 控件准备阶段
    control_addAccount = auto.ButtonControl(searchDepth=40, Name="添加账号") # 若存在，需要点击
    control_useAccount = auto.ButtonControl(searchDepth=40, Name="账密登录") # 若存在，需要点击

    control_inputAccount = auto.ComboBoxControl(searchDepth=30, Name="输入QQ号") # 用于输入QQ账号的控件
    control_inputPassword = auto.TextControl(searchDepth=30, Name="输入QQ密码") # 用于输入QQ密码的text文本控件

    # 循环5次
    num = 0
    while num <= 4:
        num += 1
        # 若以下控件存在，需要点击一下，否则直接进行登录
        if control_addAccount.Exists():
            log(levelConstant.INFO, "当前并非账密输入面板 正在切换...")
            control_addAccount.Click()
        if control_useAccount.Exists():
            log(levelConstant.INFO, "当前并非账密输入面板 正在切换...")
            control_useAccount.Click()

        # 准备登录，若当前控件不存在
        if not control_inputAccount.Exists():
            log(levelConstant.ERROR, "当前不具备登录条件 正在重试...")
            continue

        # 点击账号框，准备输入账号
        control_inputAccount.Click()
        auto.SendKeys("{ctrl}A")
        pyautogui.write(qqNumber, interval=0.2)
        log(levelConstant.INFO, "输入账号完成 正在进行下一步...")

        # 点击密码框并输入
        control_inputPassword.Click()
        pyautogui.write(qqPassword, interval=0.3)
        log(levelConstant.INFO, "输入密码完成 正在进行下一步...")
        break

    control_userAgree = auto.TextControl(searchDepth=30, Name="已阅读并同意") # 若存在，不需要点击
    control_userLogin = auto.ButtonControl(searchDepth=30, Name="登录") # 用户登录按钮

    # 点击用户同意阅读协议
    control_userAgree.Click()
    log(levelConstant.INFO, "用户阅读协议已勾选 正在进行下一步...")
    sleep_little()
    # 点击登录按钮
    control_userLogin.Click()
    log(levelConstant.INFO, "正在登录 请稍后...")

    # 需要检测是否成功登录 => 有combox搜索框
    control_helpInfo = auto.TextControl(searchDepth=30, Name="提示")
    control_backLogin = auto.ButtonControl(searchDepth=30, Name="返回登录") # 新设备按钮

    if control_inputPassword.Exists() or control_helpInfo.Exists() or control_backLogin.Exists():
        log(levelConstant.ERROR, "输入框仍然存在 或 存在提示框 登陆失败！")
        log(levelConstant.FAILED, "=====任务失败=====")
    else:
        log(levelConstant.SUCCESS, "当前账号:{},登录成功".format(qqNumber))
        return True

    log(levelConstant.FAILED, "任务失败!")
    return False

def open_and_login_QQ():
    open_qq()
    return login_qq()

def get_weather(city):
    from weather import get_weather_by_city
    return get_weather_by_city(city, "useInput")


def report_weather_to_qq(city, groupNames=None):
    if groupNames is None:
        groupNames = ["总司部 - Admin Root"]  # 默认群组列表
    elif isinstance(groupNames, str):  # 兼容旧版单群组参数
        groupNames = [groupNames]

    results = []
    for group_name in groupNames:
        try:
            log(levelConstant.INFO, f"正在处理群组 [{group_name}]")

            # 定位群聊控件
            group_control = auto.TextControl(searchDepth=30, Name=group_name)
            if not group_control.Exists():
                msg = f"群组不存在: {group_name}"
                log(levelConstant.ERROR, msg)
                results.append(f"ERROR: {msg}")
                continue

            # 进入群聊窗口
            group_control.Click()
            sleep_little()  # 等待群窗口加载
            input_control = auto.EditControl(searchDepth=30, Name=group_name)
            input_control.Click()

            # 获取并发送天气
            weather = get_weather(city)
            auto.SendKeys(weather)
            auto.SendKeys("{Ctrl}{Enter}")

            log(levelConstant.SUCCESS, f"成功发送天气至 [{group_name}]")
            results.append(f"SUCCESS: {group_name}")
            sleep_little2()  # 防止操作过快

        except Exception as e:
            error_msg = f"处理 [{group_name}] 时发生异常: {str(e)}"
            log(levelConstant.ERROR, error_msg)
            results.append(f"ERROR: {error_msg}")

    return results

def start():
    log(levelConstant.START, "=====任务开始=====")
    go_windows()
    if not open_and_login_QQ():
        return

    report_weather_to_qq("杭州", weatherGroup)

    log(levelConstant.END, "=====任务结束=====")

if __name__ == '__main__':
    start()
